<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Java Servlets</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="jee tutorial, Java, web applications, Java Servlets">
<meta name="description" content="This part of the Java EE 5 tutorials covers Java Servlets.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Contents">Contents</a>



<h1>Java Servlets</h1>

<p>
In this part of the JEE tutorials we will introduce servlets. Servlets are 
backbones of the Java web applications.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 

<p>
A <b>servlet</b> is a specialized Java class. It is used to create 
dynamic web applications.
The servlets work on a request - response programming model. They 
accept requests and create response to the 
clients. We will work with <b>HttpServlet</b>. It is an abstraction of 
all the details of the HTTP protocol.
</p>

<p>
By using servlets, we can separate business logic from the presentation 
part of the application. 
We have access to the rich set of various java libraries. 
</p>


<h2>Simple Servlet</h2>


<p>
The following example will create a very basic java servlet. 
We define a form in our JSP file.
The form will send a request to the servlet. The servlet will 
output the parameters, we have specified 
in the form.
</p>

<div class="codehead">style.css</div>
<pre class="code">
* { font-size: 12px; font-family: Verdana }
input { border: 1px solid #ccc }
</pre>

<p>
This is a simple stylesheet, that we use in this example.
</p>

<div class="codehead">index.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;

&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
&lt;title&gt;Simple Servlet&lt;/title&gt;
&lt;link rel="stylesheet" href="style.css" type='text/css'&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;form action="SimpleServlet" method="post"&gt;
&lt;table&gt;
&lt;tr&gt;
&lt;td&gt;Name&lt;/td&gt;
&lt;td&gt;&lt;input type="text" name="name"&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Message&lt;/td&gt;
&lt;td&gt;&lt;input type="text" name="message"&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;br&gt;
&lt;input type="submit" value="submit"&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html>
</pre>

<p>
In this JSP file, we define a simple form. We have two parameters, 
name and message. These will be sent to the servlet in 
the request object.
</p>

<pre class="explanation">
&lt;form action="SimpleServlet" method="post"&gt;
</pre>

<p>
This time we don't send a request to a JSP page. We send it to a servlet.
</p>

<div class="codehead">web.xml</div>
<pre class="code">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app&gt;
    &lt;servlet&gt;
        &lt;servlet-name&gt;SimpleServlet&lt;/servlet-name&gt;
        &lt;servlet-class&gt;com.zetcode.SimpleServlet&lt;/servlet-class&gt;
    &lt;/servlet&gt;
    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;SimpleServlet&lt;/servlet-name&gt;
        &lt;url-pattern&gt;/SimpleServlet&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;
    &lt;welcome-file-list&gt;
        &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
    &lt;/welcome-file-list&gt;
&lt;/web-app&gt;
</pre>

<p>
To use a servlet we must configure it in the web.xml. We define 
a servlet and a servlet mapping.
</p>


<div class="codehead">sun-web.xml</div>
<pre class="code">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;sun-web-app&gt;
  &lt;context-root&gt;/servlets&lt;/context-root&gt;
&lt;/sun-web-app&gt;
</pre>

<p>
Here we define the <b>context root</b>. The context root uniquely 
identifies a web application in a JEE server. 
We can have several modules deployed on the server. The context 
root is their id. 
</p>

<pre class="code">
protocol://host:port/contextroot/servletname
http://localhost:8080/servlets/SimpleServlet
</pre>

<p>
This is the path to our servlet. This path will be in the location bar 
of the web browser if we click on the submit
button of our form. We can call the servlet manually by simply typing 
the path to the location bar. In this case, 
we won't have any output, because the parameters are not set.
</p>


<div class="codehead">SimpleServlet.java</div>
<pre class="code">
package com.zetcode;

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;


public class SimpleServlet extends HttpServlet {


    protected void processRequest(HttpServletRequest request, 
                                  HttpServletResponse response)
                                      throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();

        String name = request.getParameter("name");
        String message = request.getParameter("message");

        try {
            out.println("&lt;html&gt;");
            out.println("&lt;head&gt;");
            out.println("&lt;title&gt;SimpleServlet&lt;/title&gt;");  
            out.println("&lt;link rel='stylesheet' href='style.css' type='text/css'&gt;");
            out.println("&lt;/head&gt;");
            out.println("&lt;body&gt;");
            if (name!=null &amp;&amp; message!=null) {
                out.println(name + " Says:");
                out.println(message);
            }
            out.println("&lt;/body&gt;");
            out.println("&lt;/html&gt;");

        } finally { 
            out.close();
        }
    }

    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response)
                             throws ServletException, IOException {
        processRequest(request, response);
    }


    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
                              throws ServletException, IOException {
        processRequest(request, response);
    }
}
</pre>

<p>
This is the servlet that will handle the request from the client. The 
template of the class was created automatically by the Netbeans IDE. I have simplified it a bit. 
We can have two HTTP methods. GET and POST. The <code>doGet()</code> 
method reacts to the GET method and  <code>doPost()</code> to the
POST method. Usually we don't distinguish between them, so each of the two methods
calls the <code>processRequest()</code> method. The doGet() 
and doPost() methods are called <b>service methods</b>. There are 4 other service methods, 
but they are not used often.
</p>

<pre class="explanation">
protected void processRequest(HttpServletRequest request, 
                            HttpServletResponse response)
</pre>

<p>
The method takes two parameters. The request object and the response 
object. The job of a service method is to extract data from the request, 
access external resources if nessasary (e.g. a database) and
populate a respose object.
</p>

<pre class="explanation">
response.setContentType("text/html;charset=UTF-8");
</pre>

<p>
Here we specify the mime type and encoding. We will send back to the 
client html content in UTF-8 encoding.
</p>

<pre class="explanation">
PrintWriter out = response.getWriter();
</pre>

<p>
We get the output stream. The html data is textual data. That's why we 
work with <code>PrintWriter</code> If we need to work with binary data, we use a 
<code>ServletOutputStream</code> class. (For example, when
we want to send an image.)
</p>

<pre class="explanation">
String name = request.getParameter("name");
String message = request.getParameter("message");
</pre>

<p>
We get the parameters from the request, that we have sent from the 
form in the index.jsp page.
</p>

<pre class="explanation">
out.println("&lt;html&gt;");
out.println("&lt;head&gt;");
out.println("&lt;title&gt;SimpleServlet&lt;/title&gt;");  
out.println("&lt;link rel='stylesheet' href='style.css' type='text/css'&gt;");
out.println("&lt;/head&gt;");
out.println("&lt;body&gt;");
if (name!=null &amp;&amp; message!=null) {
    out.println(name + " Says:");
    out.println(message);
}
out.println("&lt;/body&gt;");
out.println("&lt;/html&gt;");
</pre>

<p>
We create a html page by calling <code>println()</code> method 
on the output stream.
</p>


<h2>Using NetBeans</h2>

<p>
We will use NetBeans to create, build and deploy our example.
</p>

<img src="/img/java/jee/newwebapp.png" alt="Create web application">
<div class="figure">Figure: Create web application</div>

<p>
First by clicking on the File - New Project... or pressing 
Ctrl + Shift + N we start a new project in NetBeans IDE.
NetBeans will create a new standard project. It will create 
ant scripts to automatically build, run and debug our
project.
</p>

<img src="/img/java/jee/appname.png" alt="Name and location">
<div class="figure">Figure: Name and location of a project</div>


<p>
Next we select a name and location for our project. We also can select 
a Java EE version and server name. We can choose among Tomcat and 
GlassFish by default. We will work with GlassFish. We won't work with frameworks for now,
so we can already click on the finish button. Frameworks will be 
menioned later in our JEE tutorials
</p>

<img src="/img/java/jee/newservlet.png" alt="New Servlet">
<div class="figure">Figure: New Servlet</div>


<p>
By right clicking on the name of the web application in the Projects window, 
we can select a new Servlet.
</p>

<img src="/img/java/jee/namelocat.png" alt="Name and location of a servlet">
<div class="figure">Figure: Name and location of a servlet</div>

<p>
We specify the name of a servlet and a location path. The name of our servlet 
will be SimpleServlet. We also provide a package name for this servlet.
</p>


<img src="/img/java/jee/configureservlet.png" alt="Servlet configuration">
<div class="figure">Figure: Servlet configuration</div>

<p>
Here we specify the servlet mapping. This will be written to the web.xml file.
</p>

<img src="/img/java/jee/run.png" alt="Running application">
<div class="figure">Figure: Running application</div>


<p>
Finally we run the application. Press the green triangle in the build toolbar, 
or press <b>F6</b>. This will build the application, start a server if necesarry 
and deploy it on the server.
</p>


<p>
In this chapter we worked with Java Servlets.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br> 


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified February 14, 2008  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>


